package com.hkd.common.api.interceptor;

import com.hkd.common.api.SysException;
import com.hkd.common.api.anntation.Idempotent;
import com.hkd.common.api.constants.CacheConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 幂等拦截器
 * 需要使用时配置webmvc
 */
@Component
@Lazy
public class IdempotentInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Idempotent idempotent;
        idempotent=method.getAnnotation(Idempotent.class);
        if (idempotent!=null) {
            String userId = request.getHeader("userId");
            if (StringUtils.isNotEmpty(userId)){
                String keyValue= CacheConstants.IDEMPOTENT+userId+idempotent.keyValue();
                boolean flag = redisTemplate.opsForValue().setIfAbsent(keyValue,keyValue,idempotent.time(), TimeUnit.MILLISECONDS);
                if (!flag){
                    throw new SysException("请勿频繁操作");
                }
            }
        }
        return true;
    }
}
